local prefix = 'generator:id:';
local logical_shard_id_key =  prefix..'logical-shard-id'

-- 第一个KEY是model，或者是table name
local tag = KEYS[1];
-- eg : generator:id:user:lock
local lock_key = prefix..tag..':lock'
-- eg : generator:id:user:sequence
local sequence_key =  prefix..tag..':sequence'

local max_sequence = tonumber(KEYS[2])
--local min_logical_shard_id = tonumber(KEYS[2])
--local max_logical_shard_id = tonumber(KEYS[3])
local num_ids = tonumber(KEYS[3])

if redis.call('EXISTS', lock_key) == 1 then
  -- redis.log(redis.LOG_NOTICE, 'Id-Generator: Can not generator id. please wait lock expire.')
  return redis.error_reply('Id-Generator: Can not generator id. please wait lock expire.')
end

--[[
递增序列号，num_ids表示要获得的ID数量，所以序列号将递增相应的值
--]]
local end_sequence = redis.call('INCRBY', sequence_key, num_ids)
local start_sequence = end_sequence - num_ids + 1
local logical_shard_id = tonumber(redis.call('GET', logical_shard_id_key)) or -1

if end_sequence >= max_sequence then
  -- redis.log(redis.LOG_NOTICE, 'Id-Generator: 回滚递增序列号值为默认起始值，并加锁 - 1ms.')
  -- redis.log(redis.LOG_NOTICE, 'end_sequence: '..end_sequence)
  redis.call('SET', sequence_key, '-1')
  -- redis.call('PSETEX', lock_key, 1, 'lock')
  redis.call('SET', lock_key, 'lock', 'PX', 1)
  end_sequence = max_sequence
end

--[[
最后执行time命令，获得数据:[seconds, microSeconds]
--]]
local time = redis.call('TIME')
return {tonumber(time[1]), tonumber(time[2]),start_sequence,end_sequence,logical_shard_id}
